package com.onpositive.realmview;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

import com.onpositive.semantic.model.realm.HashDelta;
import com.onpositive.semantic.model.realm.IDisposable;
import com.onpositive.semantic.model.realm.IRealm;
import com.onpositive.semantic.model.realm.IRealmChangeListener;
import com.onpositive.semantic.model.realm.ISetDelta;
import com.onpositive.semantic.model.realm.ITransformer;

public abstract class ReplacingRealm<T> implements IRealm<T>, IRealmChangeListener<T>,IDisposable{


	protected IRealm<T>owner;
	
	public ReplacingRealm(IRealm<T>own){
		owner=own;
		owner.addRealmChangeListener(this);
	}
	
	HashSet<IRealmChangeListener<?>>z=new HashSet<IRealmChangeListener<?>>();
	
	public boolean contains(Object o) {
		if (owner.contains(replaceBack(o))){
			return true;
		}		
		return false;
	}

	public Collection<T> getContents() {
		Collection<T> contents = owner.getContents();
		ArrayList<T>r=new ArrayList<T>(contents.size());
		for (T q:contents){
			r.add(doReplace(q));
		}
		return r;
	}
	
	@SuppressWarnings("unchecked")
	public void realmChanged(IRealm<T> realmn, ISetDelta<T> delta) {
		HashDelta z=(HashDelta) delta;
		HashDelta transform = z.transform(new ITransformer<T, T>() {

			public T transform(T object) {				
				return doReplace(object);
			}
		});
		for (IRealmChangeListener q:this.z){
			q.realmChanged(realmn, transform);
		}
	}
	

	
	public void addRealmChangeListener(IRealmChangeListener<T> listener) {
		z.add(listener);
	}
	public void removeRealmChangeListener(IRealmChangeListener<T> listener) {
		z.remove(listener);
	}



	public IRealm<T> getParent() {
		return owner;
	}

	public boolean isOrdered() {
		return owner.isOrdered();
	}


	public int size() {
		return owner.size();
	}

	public Iterator<T> iterator() {
		final Iterator<T> iterator = owner.iterator();
		return new Iterator<T>() {

			public boolean hasNext() {
				return iterator.hasNext();
			}

			public T next() {
				T next = iterator.next();
				next=doReplace(next);
				return next;
			}

			public void remove() {
				iterator.remove();
			}
		};
	}
	protected abstract T doReplace(T next);
	
	protected abstract T replaceBack(Object next);

	public void dispose(){
		owner.removeRealmChangeListener(this);
	}
}
